<?php

class Db {

	private $_link;

	public function link () {
		if ($this->_link === null) {
			$this->_link = mysql_connect(App::inst()->config['db']['host'], App::inst()->config['db']['user'], App::inst()->config['db']['password']);
			if(!$this->_link) throw new Exception('Can`t connect to mysql. ' . mysql_error());
	
			if(!mysql_select_db(App::inst()->config['db']['db'], $this->_link)) throw new Exception('Can`t select mysql db: ' . mysql_error());
			
			if(App::inst()->config['db']['charset']) $this->q("SET NAMES ". App::inst()->config['db']['charset']);
		}
		return $this->_link;
	}

	public function q ($q) {
		$result = mysql_query($q, $this->link());
		if(!$result) throw new Exception('Can`t execute query. Mysql return error: ' . mysql_error());
		
		return $result;
	}
	
	/**
	 * @param string $modelName
	 * @return Db_Record
	 */
	public static function model($modelName, $event = Db_Record::EVENT_NEW){
		$model = preg_match("|^M[A-Z]|", $modelName) ? $modelName : "M{$modelName}";
		return new $model($event);
	}

}